import baseUrl from '../config/url.js'
import {
	baseUrlReg
} from './reg.js'

export default function(option) {
	return new Promise((resolve, reject) => {
		console.log(option)
		uni.request({
			url: baseUrlReg.test(option.url) ? option.url : baseUrl + option.url,
			method: option.method,
			withCredentials: true,
			timeout: 1000 * 30,
			data: typeof option.data === 'string' ? option.data : {
				...option.data
			},
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				...option.header
			},
			success: (res) => {
				if (res.statusCode == 200) {
					if (typeof res.data == "string" && res.data.indexOf("err@") == 0) {
						if (res.data.includes('err@登录信息丢失')) {
							uni.showToast({
								title: '登录信息丢失，请重新登录',
								icon: 'none'
							})
							reject(res.data)
						} else {
							uni.showToast({
								title: res.data,
								icon: 'none'
							})
							reject(res.data)
						}
					} else {
						resolve(res.data)
					}

				} else {
					reject(res.data)
				}
			},
			fail: (err) => {
				if (err && err.errMsg) {
					uni.hideLoading()
					uni.showToast({
						title: err.errMsg,
						icon: 'none'
					})
				} else {
					uni.showToast({
						title: '网络异常',
						icon: 'none'
					})
				}
				reject(err)
			}
		});
	})
}
